<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {resetPasswordService} from '@/api/user.js'
import userUserInfoStore from "@/stores/userInfo.js";
import {userTokenStore} from "@/stores/token.js";

const tokenStore = userTokenStore();
import router from "@/router/index.js";


const userInfoStore = userUserInfoStore();
const resetPassword = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const updatePassword = async () => {
  //调用接口
  let result = await resetPasswordService(resetPassword.value);
  ElMessage.success(result.msg ? result.msg : '修改成功')
  //退出登录
  //1.清空pinia中存储的token以及个人信息
  tokenStore.removeToken();
  userInfoStore.removeInfo();
  //2.跳转到登录页面
  await router.push('/login')
}


const rules = {
  oldPassword: [
    {required: true, message: '请输入旧密码', trigger: 'blur'},
    // 可以添加更多规则，如特殊字符要求等
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, max: 16, message: '密码长度必须在6到16个字符之间', trigger: 'blur'},
    // 可以添加更多规则，如特殊字符要求等
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {validator: validatePasswords, trigger: 'blur'}
  ]
}

function validatePasswords(rule, value, callback) {
  if (value !== resetPassword.value.confirmPassword) {
    callback(new Error('两次输入的密码不一致!'));
  } else {
    callback();
  }
}


</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>重置密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form :model="resetPassword" :rules="rules" label-width="100px" size="large">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input type="password" v-model="resetPassword.oldPassword"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="resetPassword.newPassword"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="resetPassword.confirmPassword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword(resetPassword)">重置密码</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>

<style scoped>
/* 你可以在这里添加一些样式 */
</style>